package com.example.demo.service;

import com.example.demo.converter.UserConverter;
import com.example.demo.converter.UserDetailConverter;
import com.example.demo.dao.*;
import com.example.demo.dto.UserDTO;
import com.example.demo.dto.UserDetailDTO;
import org.hibernate.service.spi.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private UserDetailService userDetailService;
    @Autowired
    private ImageService imageService;
    @Override
    public UserDTO getUserById(long id) {
        User user=userRepository.findById(id).orElseThrow(RuntimeException::new);
        UserDetail userDetail=user.getUserDetail();
        try {
            UserDetailDTO userDetailDTO = UserDetailConverter.convertUserDetail(userDetail);
            String imageName = userDetailDTO.getImageName();
            if (imageName != null && !imageName.isEmpty()) {
                byte[] imageBytes = imageService.getImageAsBytes(imageName);
                userDetailDTO.setImageBytes(imageBytes);
            }
            UserDTO userDTO=UserConverter.convertUser(user);
            userDTO.setUserDetailDTO(userDetailDTO);
            return userDTO;
        } catch (IOException e) {
            throw new ServiceException("Error retrieving image for Cloth", e);
        } catch (Exception e) {
            throw new ServiceException("Error converting Cloth to ClothDTO", e);
        }
    }

    @Override
    public UserDTO getUserByName(String name) {
        if (name==null||StringUtils.hasLength(name)){
            throw new IllegalArgumentException("name is empty");
        }
        User user=userRepository.findByName(name);
        return UserConverter.convertUser(user);
    }

    @Override
    public Long addNewUser(UserDTO userDTO) {
        // 检查邮箱是否已被注册
        if (userDTO.getEmail() != null) {
            List<User> userEmailList = userRepository.findByEmail(userDTO.getEmail());
            if (!CollectionUtils.isEmpty(userEmailList)) {
                throw new IllegalStateException("Email: " + userDTO.getEmail() + " has been taken");
            }
        }
        // 检查电话号码是否已被注册
        if (userDTO.getPhoneNumber() != null) {
            List<User> userPhoneNumberList = userRepository.findByPhoneNumber(userDTO.getPhoneNumber());
            if (!CollectionUtils.isEmpty(userPhoneNumberList)) {
                throw new IllegalStateException("PhoneNumber: " + userDTO.getPhoneNumber() + " has been taken");
            }
        }
        // 将 UserDTO 转换为 User 对象并保存到数据库
        User user = userRepository.save(UserConverter.convertUser(userDTO));

        // 创建一个空的 UserDetailDTO 对象，并保存到用户详细信息表中
        UserDetailDTO userDetailDTO = new UserDetailDTO();
        userDetailService.addNewUserDetailByUserId(user.getId(), userDetailDTO);

        // 返回保存用户后的用户ID
        return user.getId();
    }

    @Override
    public void deleteUserById(long id) {
        userRepository.findById(id).orElseThrow(()->new IllegalArgumentException("id:"+id+"doesn't exist!"));
        userRepository.deleteById(id);
    }

    @Override
    public UserDTO updateUserById(long id, String name, String password, String email, String phoneNumber,String account) {
        User userInDB=userRepository.findById(id).orElseThrow(()->new IllegalArgumentException("id:"+id+"doesn't exist!"));
        if (userInDB.getName()==null||(StringUtils.hasLength(name)&& !userInDB.getName().equals(name))){
            userInDB.setName(name);
        }
        if (userInDB.getEmail()==null||(StringUtils.hasLength(email)&& !userInDB.getEmail().equals(email))){
            userInDB.setEmail(email);
        }
        if (userInDB.getAccount()==null||(StringUtils.hasLength(account)&& !userInDB.getAccount().equals(account))){
            userInDB.setAccount(account);
        }
        if (userInDB.getPhoneNumber()==null||(StringUtils.hasLength(phoneNumber)&& !userInDB.getPhoneNumber().equals(phoneNumber))){
            userInDB.setPhoneNumber(phoneNumber);
        }
        if (StringUtils.hasLength(password)&& !userInDB.getPassword().equals(password)){
            userInDB.setPassword(password);
        }
        User user=userRepository.save(userInDB);
        return UserConverter.convertUser(user);
    }

    @Override
    public UserDTO getUserByAccount(String account) {
        return UserConverter.convertUser(userRepository.findByAccount(account));
    }
}
